import {ref} from 'vue'
import {defineStore} from 'pinia'
import {login} from '@/apis/user.js'
import {useCartStore} from './cart.js'
import {mergerCartAPI} from '@/apis/cart.js'

export const useUserStore = defineStore('user', () => {
        const cartStore = useCartStore()
        const userInfo = ref({})
        const getUserInfo = async ({account, password}) => {
                const res = await login({account, password})
                userInfo.value = res.data.result
                // 合并购物车操作
                await mergerCartAPI(cartStore.cartList.map(item => {
                        return {
                                skuId: item.skuId,
                                selected: item.selected,
                                count: item.count
                        }
                }))
                await cartStore.getList()
        }
        // 退出时清除用户信息
        const clearUserInfo = () => {
                userInfo.value = {}
                // 清除购物车数据
                cartStore.clearCart()
        }
        return {
                userInfo, getUserInfo, clearUserInfo
        }
}, {
        persist: true,
},)
